<?php
/**
 * Created by PhpStorm.
 * User: x
 * Date: 2018/10/27
 * Time: 15:03
 */

namespace app\newapi\controller;

use app\common\controller\HomeBase;
use app\common\model\Kefu as KefuModel;
use app\common\model\Csuser as CsuserModel;
// 常用回复
use app\common\model\Csuserwords as CsWordsModel;
use app\common\model\AuthorWxUser as AuthorWxUserModel;
use think\Session;
use app\common\model\Users as UsersModel;
use think\Db;
use app\common\util\WechatThirdUtil;

class Fans extends HomeBase{
    protected $users_model;
    protected $config;
    protected $wechat_obj;
    protected $author_config;
    protected $csuser_model;

    protected function _initialize()
    {
        parent::_initialize();
        $this->author_config = session::get('wechat_info');
        $this->users_model = new UsersModel();
        $this->config = Db::name('wx_user')->find();
        $this->csuser_model = new CsuserModel();
    }

    /*
     * 获取所有粉丝
     * */
    public function all($start_time = '',$end_time = '',$page = 1,$keyword = '',$auid=0){
        $where = [];
        if(!empty($start_time) && !empty($end_time)){
            $where = [
                'subscribe_time'=>['between',[$start_time,$end_time]],
            ];
        }
        if (!empty($keyword)) {
            $where['think_users.nickname'] = ['like','%'.$keyword.'%'];
        }
        if(! $auid){
            $where['think_users.auid'] = ['eq',$this->author_config['id']];
        }
        $result = $this->users_model
            ->field('u.butt_id,u.sex,u.subscribe_time,u.unsubscribe_time,u.subscribe,u.openid,u.headimgurl,u.nickname,think_csuser.nickname as cs_nickname')
            ->alias('u')
            ->join('think_csuser','u.butt_id = think_csuser.id','left')
            ->where($where)
            ->order('subscribe_time desc')
            ->paginate(15,false,['page'=>$page]);
        return json(['status' => 1,'data' => $result, 'key'=> [
            'keyword' => $keyword,
            'page' => $page,
            'start_time' => $start_time,
            'end_time' => $end_time
        ]]);
    }

    /*
     * 20190306 aebell
     * 根据性别和地区搜索用户列表
     * */
    public function getFansByPart($sex=0,$city='',$isvalue=0,$auid=0,$province=''){
        $map = [];

        if($sex){
            if($sex == 1){
                $map['sex'] = 1;
            }else{
                $map['sex'] = 2;
            }
        }
        if(! empty($province)){
            $map['province'] = $province;
        }
        if(! empty($city)){
            $map['city'] = $city;
        }
        if($auid){
            $map['auid'] = $auid;
        }else{
            return json('id 不能为空');
        }
        if($isvalue){
            $result = Db::name('users')->field('nickname,openid,headimgurl')->where($map)->select();
        }else{
            $result = Db::name('users')->where($map)->column('openid');
        }
        return json($result);
    }


    // 标签的
    /**
     * 获取标签下粉丝列表
     */
    public function getTagFansList($tagid,$next_openid = '',$auid=0){
        if($auid){
            $where = [  'uid'=>['eq',1],   'id' => ['eq',$auid],   ];
            $wechat_info = Db::name('author_wx_user')->where($where)->find();
            $this->wechat_obj = new WechatThirdUtil($this->config , $wechat_info);
        }else{
            return json('id 不能为空');
        }
        $wechat_obj = $this->wechat_obj;
        $result = $wechat_obj->getTagUsersList($tagid,$next_openid);
        return json($result);
    }

    /*
     * 获取图文素材列表
     * type 是 素材的类型，图片（image）、视频（video）、语音 （voice）、图文（news）
        offset 是 从全部素材的该偏移位置开始返回，0表示从第一个素材 返回
        count 是 返回素材的数量，取值在1到20之间
     * */
    public function listText($type = 'news', $offset=0, $count=20,$auid=0){
        if($auid){
            $where = [  'uid'=>['eq',1],   'id' => ['eq',$auid],   ];
            $wechat_info = Db::name('author_wx_user')->where($where)->find();
            $this->wechat_obj = new WechatThirdUtil($this->config , $wechat_info);
        }else{
            return json('id 不能为空');
        }
        $result = $this->wechat_obj->getMaterialList($type, $offset, $count);
        return json($result);
    }

    /*
     * 回复图文消息
     * */
    public function replyText($openid='',$media_id='',$auid=0){
        if($auid){
            $where = [  'uid'=>['eq',1],   'id' => ['eq',$auid],   ];
            $wechat_info = Db::name('author_wx_user')->where($where)->find();
            $this->wechat_obj = new WechatThirdUtil($this->config , $wechat_info);
        }else{
            return json('id 不能为空');
        }
        $result = $this->wechat_obj->sendImgMsgToOne($openid, $media_id);
        return json($result);
    }

    // 存储模板消息发送情况
    public function templateStatus($auid=0,$tid=0,$message=''){
        $list = ['uid'=>$auid,'title'=>$tid,'message'=>$message,'create_time'=>time()];
        $result = Db::name('pushmessage')->insertGetId($list);
        return json($result);
    }

    // 查询模板消息发送记录
    public function searchTemplate($auid=0){
        if($auid){
            $result = Db::name('pushmessage')->where('uid',$auid)->select();
            return json($result);
        }else{
            return json('id不能为空');
        }
    }

    // 通过呢称搜索对应的openid
    public function wxOpenid($nickname='',$page=1,$auid = 111){
        $map = [
            'auid' => $auid,
            'subscribe' => 1
        ];
        $field = 'user_id,nickname,sex,openid';
        if(empty($nickname)){
            // 返回15个最新的关注用户
            $result = $this->users_model->field($field)->where($map)->order(['user_id' => 'DESC'])->paginate(15, false, ['page' => $page]);
            return json($result);
        }else{
            $map['nickname'] = ['like', "%{$nickname}%"];
            $result = $this->users_model->field($field)->where($map)->paginate(15, false, ['page' => $page]);
            return json($result);
        }
    }

    //
    public function wxnotice($type=0,$keyword='',$pid=0,$page=1){
        // 区分手机号和公众号openid提醒
        $result_list = [];
        if($type){
            if($type == 1){
                $result_wx = Db::name('wxurlnotice')->alias('w')
                    ->field('w.id,w.auid,w.notice,w.pid,w.remark,think_users.nickname')
                    ->where(['type'=>1])
                    ->join('think_users','w.notice = think_users.openid')
                    ->paginate(15, false, ['page' => $page]);
                $result_list['wx'] = $result_wx;

            }else{
                $result_phone = Db::name('wxurlnotice')
                    ->field('id,auid,notice,pid,remark')
                    ->where(['type'=>2])
                    ->paginate(15, false, ['page' => $page]);
                $result_list['phone'] = $result_phone;
            }
        }
        $result_wx = Db::name('wxurlnotice')->alias('w')
            ->field('w.id,w.auid,w.notice,w.pid,w.remark,think_users.nickname')
            ->where(['type'=>1])
            ->join('think_users','w.notice = think_users.openid')
            ->select();
        $result_phone = Db::name('wxurlnotice')
            ->field('id,auid,notice,pid,remark')
            ->where(['type'=>2])
            ->select();
        return json(['wx'=>$result_wx,'phone'=>$result_phone]);
    }

    // ------------  粉丝数据统计
    /*
     * 客服对应的粉丝 总客户/关注人数
     * 组长看到总的数量和所管理的组员的数量
     * @aeball
     * @date  20190314
     * */
    public function fansData($auid=0,$cs_id=0){
        $cs_info = $this->csuser_model
//            ->field('id,pid,auid,username,nickname')
            ->where('id',$cs_id)->value('pid');
        if($cs_info){
            // 组员账户, 显示自己的用户信息
            $map = ['auid' => $auid, 'butt_id' =>$cs_id];
            $fans_data = $this->users_model->where($map)->count();
            // follow
            $map['subscribe'] = 1;
            $fans_follow = $this->users_model->where($map)->count();
            $map['groupid'] = 1;
            $fans_talk = $this->users_model->where($map)->count();
            $map['sex'] = 1;
            $fans_man = $this->users_model->where($map)->count();
            $map['sex'] = 2;
            $fans_woman = $this->users_model->where($map)->count();
            return json(['cs_id' => $cs_id,
                'data' => ['all' => $fans_data,'follow'=>$fans_follow,'istalk'=>$fans_talk,'man'=>$fans_man,'woman'=>$fans_woman]]);
        }else{
            //查找pid对应的所有子账号
            $cs_group = $this->csuser_model->where('pid',$cs_id)->select();
            $cs_group_list = [];
            foreach ($cs_group as $cs_member) {
                $map = ['auid' => $auid, 'butt_id' =>$cs_member['id']];
                // all
                $fans_data = $this->users_model->where($map)->count();
                // follow
                $map['subscribe'] = 1;
                $fans_follow = $this->users_model->where($map)->count();
                $map['groupid'] = 1;
                $fans_talk = $this->users_model->where($map)->count();
                $map['sex'] = 1;
                $fans_man = $this->users_model->where($map)->count();
                $map['sex'] = 2;
                $fans_woman = $this->users_model->where($map)->count();
                array_push($cs_group_list,['cs_id' => $cs_id,
                    'data' => ['all' => $fans_data,'follow'=>$fans_follow,'istalk'=>$fans_talk,'man'=>$fans_man,'woman'=>$fans_woman]]);
            }
            $map_all = ['auid' => $auid, 'butt_id' =>$cs_id];
            // all
            $fans_data = $this->users_model->where($map_all)->count();
            // follow
            $map_all['subscribe'] = 1;
            $fans_follow = $this->users_model->where($map_all)->count();
            $map_all['groupid '] = 1;
            $fans_talk = $this->users_model->where($map_all)->count();
            $map_all['sex'] = 1;
            $fans_man = $this->users_model->where($map_all)->count();
            $map_all['sex'] = 2;
            $fans_woman = $this->users_model->where($map_all)->count();
            array_push($cs_group_list,['cs_id' => $cs_id,
                'data' => ['all' => $fans_data,'follow'=>$fans_follow,'istalk'=>$fans_talk,'man'=>$fans_man,'woman'=>$fans_woman]]);
            return json($cs_group_list);
        }

    }




}